//全局变量区
var searchDiv    = document.getElementById('searchDivSc');
searchCompSc   = document.getElementById('autoCompleteSc');
searchNameSc   = document.getElementById('searchNameSc');
isOnAutoCompSc = false;//鼠标是否在自动补全列表上
//*****

//监听器事件区
searchNameSc.addEventListener('keyup',onSearchKeyUp);//输入结束时，查询，显示
searchNameSc.addEventListener('blur',onSearchBlur);//失去焦点时，隐藏
searchCompSc.addEventListener('mouseenter',setTrue);
searchCompSc.addEventListener('mouseleave',setFalse);//鼠标进入离开
//*****

//自动补全部分代码
function onSearchKeyUp(){
  $('#autoCompleteLiSc').empty();//先清空

  var searchString = $('#searchNameSc').val();//获取当前输入框的字符
  //console.log(searchString);

  //如果有输入的话，查询
  if(searchString !== '' && searchString.length !== 0){
    $.ajax({
      type:'GET',
      url :'http://localhost:8080/petstore/autoComplete?searchString='+searchString,
      success : function (data){
        var dataJson = JSON.parse(data);//取得响应，转换为JSON
        var autoInnerHtml='';
        //console.log(dataJson);
        $('#autoCompleteLiSc').empty();//先清空
        //循环取值，拼接并显示
        for(var i in dataJson){
          if(i>6) break;//超过7个则停止
          autoInnerHtml+='<ul class=\"searchCompUl\" data-name=\"'
              +dataJson[i].name+'\">'
              +dataJson[i].name+'</ul>';//拼接
        }
        $('#autoCompleteLiSc').append(autoInnerHtml);//添加
      },
      error : function (errorMsg){
        console.log(errorMsg);
      },
    });
    searchCompSc.style.display="block";//显示出来
  }
}//查询并显示

$('#autoCompleteLiSc').on('click','.searchCompUl',function (){
  var autoCompleteName = $(this).data('name');
  $('#searchNameSc').val(autoCompleteName);
  //补全至搜索框后，清空并隐藏
  $("#autoCompleteUlSc").empty();
  searchCompSc.style.display="none";
});//动态绑定点击事件

function onSearchBlur(){
  if(!isOnAutoCompSc){
    console.log(isOnAutoCompSc);
    $("#autoCompleteUlSc").empty();
    searchCompSc.style.display="none";
  }
}//清空并隐藏

//设置是否处于自动补全div内状态
function setFalse(){
  isOnAutoCompSc=false;
}
function setTrue(){
  isOnAutoCompSc=true;
}
//*****